package cn.office.utils;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.json.JSONUtil;
import cn.office.param.PdfGenerateParam;
import com.itextpdf.text.pdf.BaseFont;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Properties;

@Slf4j
public class PdfUtils {

    private PdfUtils(){}
    /**
     * 将数据列表导出为pdf格式
     * @param pdfGenerateParam
     * @param outputStream
     * @return
     */
    public static void createPdf(PdfGenerateParam pdfGenerateParam, OutputStream outputStream)
            throws IOException, com.lowagie.text.DocumentException {
        log.info("生成PDF文件入参:{}", JSONUtil.toJsonStr(pdfGenerateParam));
        Instant now = Instant.now();
        Properties properties = new Properties();
        properties.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
        properties.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        properties.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        properties.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        properties.setProperty(Velocity.FILE_RESOURCE_LOADER_CACHE, "true");
        properties.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");
        try {
            Velocity.init(properties);
        } catch (Exception e) {
            log.error("初始化模版失败!",e);
        }

        //获取模版
        Template template = Velocity.getTemplate(pdfGenerateParam.getTemplateName());
        template.setEncoding("utf-8");
        StringWriter writer = new StringWriter();
        template.merge(pdfGenerateParam.getVelocityContext(), writer);

        //IText生成pdf
        ITextRenderer renderer = new ITextRenderer();
        ITextFontResolver fontResolver = renderer.getFontResolver();

        try{
            String property = System.getProperty("os.name").toLowerCase();
            if(!property.contains("windows")){
                fontResolver.addFont("/usr/share/fonts/dejavu/SIMSUN.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            }else {
                fontResolver.addFont("C:/windows/fonts/SIMSUN.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            }
        }catch (Exception e){
        	ClassPathResource resource = new ClassPathResource("/fonts/simsun.ttc");
            fontResolver.addFont(resource.getAbsolutePath(),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        }
        renderer.setDocumentFromString(writer.toString());

        //生成pdf文件
        try (OutputStream os = outputStream) {
            renderer.layout();
            renderer.createPDF(os);
        }catch(Exception ex) {
        	ex.printStackTrace();
        }
        log.info("生成PDF文件: 耗时：{}毫秒", ChronoUnit.MILLIS.between(now, Instant.now()));

    }
}
